<template>
  <div class="upload-img">
    <div v-if="imageUrl" class="bese-box" :style="`width: ${width}px; height: ${height}px`">
      <img class="bese-img" :src="src" :class="{ 'edit-flag': editFlag }" alt="" />
      <div v-if="!editFlag" class="bese-bgc" :class="{ 'edit-flag': editFlag }">
        <div><i class="el-icon-delete" @click.stop="handleRemove"></i></div>
      </div>
    </div>
    <ElUpload
      v-else
      :accept="accept"
      :disabled="editFlag"
      :data="{ unid: unid, type: 'content' }"
      class="avatar-uploader"
      auto-upload
      :action="getUploadUrl()"
      :headers="getHeader()"
      :show-file-list="false"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload">
      <img v-if="imageUrl" :src="src" class="avatar" :class="{ 'edit-flag': editFlag }" />
      <i
        v-else
        class="el-icon-plus avatar-uploader-icon"
        :style="`width: ${width}px; height: ${height}px; line-height: ${height}px;`"
        :class="{ 'edit-flag': editFlag }"></i>
    </ElUpload>
  </div>
</template>

<script>
  import { getHeader, getUploadUrl } from '@/api/attachment/attachment'
  import { guid } from '@web-utils/core'

  export default {
    name: 'UploadImg',
    props: {
      editFlag: Boolean,
      unid: String,
      value: String,
      fileType: {
        type: Array,
        default: () => ['image/jpg', 'image/jpeg', 'image/png']
      },
      width: {
        type: [String, Number],
        default: 178
      },
      height: {
        type: [String, Number],
        default: 178
      }
    },
    data() {
      return {
        imageUrl: '',
        baseimageUrl: window.imageUrl || process.env.VUE_APP_IMAGE_URL
      }
    },
    computed: {
      accept() {
        let str = ''
        const arr = this.fileType.map(item => {
          return `.${item.substring(item.lastIndexOf('/') + 1, item.length)}`
        })
        str = arr.join(',')
        return str
      },
      src() {
        return this.imageUrl ? `${this.baseimageUrl}/${this.imageUrl}` : ''
      }
    },
    watch: {
      value: {
        immediate: true,
        handler(imgUrl) {
          this.imageUrl = imgUrl
        }
      }
    },
    methods: {
      guid,
      getHeader,
      getUploadUrl,
      handleAvatarSuccess(res, file) {
        this.imageUrl = URL.createObjectURL(file.raw)
        if (res.data) {
          let fileUrl = res.data.fileUrl
          if (fileUrl.indexOf('\\') > -1) {
            fileUrl = fileUrl.replaceAll('\\', '/')
          }
          const imgUrl = fileUrl.substr(fileUrl.indexOf('/merge/') + 7)
          this.$emit('input', imgUrl)
        }
      },
      beforeAvatarUpload(file) {
        const isJPG = this.fileType.includes(file.type)
        const isLt2M = file.size / 1024 / 1024 < 2

        if (!isJPG) {
          // const msg = this.fileType.map(item => {
          //   return item.
          // })
          this.$message.error(`上传图片只能是 ${this.accept} 格式!`)
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 2MB!')
        }
        return isJPG && isLt2M
      },
      async handleRemove() {
        try {
          await this.$confirm('是否要删除已上传的照片？', '系统提醒', { type: 'warning' })
          this.imageUrl = ''
          this.$emit('input', '')
        } catch (e) {}
      }
    }
  }
</script>

<style lang="scss">
  .upload-img {
    .avatar-uploader {
      text-align: right;

      .el-upload {
        position: relative;
        overflow: hidden;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
      }
    }

    .bese-box {
      position: relative;
      float: right;
      width: 178px;
      height: 178px;
      margin-bottom: 12px;

      .bese-img {
        width: 100%;
        height: 100%;
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
      }

      .bese-bgc {
        position: absolute;
        top: 0;
        left: 0;
        display: none;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.3);
        border-radius: 6px;

        > div {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 100%;
        }

        .el-icon-delete {
          color: #fff;
          font-size: 28px;
          text-align: center;
          cursor: pointer;
        }
      }
    }

    .bese-box:hover .bese-bgc {
      display: block;
    }

    .edit-flag {
      cursor: no-drop;
    }

    .avatar-uploader .el-upload:hover {
      border-color: #409eff;
    }

    .avatar-uploader-icon {
      width: 178px;
      height: 178px;
      color: #8c939d;
      font-size: 28px;
      line-height: 178px;
      text-align: center;
    }

    .avatar {
      display: block;
      width: 100%;
      height: 100%;
    }
  }
</style>
